//
//  RHLocalBatteryCellFullChartVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/29.
//

#import "RHLocalBatteryCellFullChartVC.h"
#import "RHLocalBatteryCellChartView.h"
#import "DevChartModel.h"
#import "WSDatePickerView.h"
#import "DeviceChartFieldModel.h"
#import "RHLocalSettingModel.h"
#import "CBLECenterMnger.h"
#import "RHBleCmdData.h"
#import "CBLEDataParse.h"
#import "RHBleCmdManager.h"
#import "JCDataConvert.h"

@interface RHLocalBatteryCellFullChartVC ()
@property (nonatomic ,strong) QMUILabel *titleLab;

@property (nonatomic ,assign) NSInteger packIndex;
//从0开始
@property (nonatomic ,assign) NSInteger cellIndex;

@property (nonatomic ,strong) RHLocalBatteryCellChartView *chartView;

@property (nonatomic ,strong) DevChartModel *chartModel;

@property (nonatomic ,strong) NSTimer *timer;

@property (nonatomic ,strong) NSArray *cmdArray;

@property (nonatomic ,strong) NSMutableDictionary *lineDic;

@property (nonatomic ,strong) NSMutableDictionary *dataDic;

@property (nonatomic ,strong) NSMutableArray *chartDataArr;


//单体电压数量
@property (nonatomic ,assign) NSInteger cellVolCount;
//单体温度数量,两个单体共用一个温度
@property (nonatomic ,assign) NSInteger cellTempCount;
//读取完电芯单体个数和温度个数
@property (nonatomic ,assign) BOOL hasReadVolTempCount;
//读取完电芯电压和温度值
@property (nonatomic ,assign) BOOL hasReadVolTempValue;
//电芯电压数据
@property (nonatomic ,strong) NSMutableArray *volDataArr;
//电芯温度数据
@property (nonatomic ,strong) NSMutableArray *tempDataArr;
@end


@implementation RHLocalBatteryCellFullChartVC

- (instancetype)initWithPackIndex:(NSInteger)packIndex  cellIndex:(NSInteger)cellIndex;
{
    self = [super init];
    if (self) {
        _packIndex = packIndex;
        _cellIndex = cellIndex;
        self.lineDic = [NSMutableDictionary dictionary];
        self.dataDic = [NSMutableDictionary dictionary];
    }
    return self;
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self startReadDeviceInfo];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self stopReadDeviceInfo];
    [ProgressHUDManage shareObject].showLoadingTips = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [ProgressHUDManage shareObject].showLoadingTips = NO;
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    NSArray *cellDataArr = @[
        @{
            @"nickname": @"Pck_CellV",
            @"comment": @"电芯电压",
            @"unit": @"mV",
            @"min": @(0),
            @"max": @(65535),
            @"type": @"number",
            @"format": @"float",
            @"alias": @"电芯电压"
        },
        @{
            @"nickname": @"Pck_Tmp",
            @"comment": @"电芯温度",
            @"unit": @"℃",
            @"min": @(-20),
            @"max": @(100),
            @"type": @"number",
            @"format": @"float",
            @"alias": @"电芯温度"
        }
    ];
    
    self.chartModel = [[DevChartModel alloc]init];
    self.chartModel.dayParams = [NSArray yy_modelArrayWithClass:[DeviceChartFieldModel class] json:cellDataArr];
    self.chartModel.params = [self.chartModel.dayParams mutableCopy];
    NSDate *date = [NSDate date];
    NSTimeInterval interval = [date timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%ld",(NSInteger)interval];
 
    [self setupUI];
    [self readVolAndTempCount];
}





-(void)startReadDeviceInfo
{
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(readCellVoltageAndTemperature) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)stopReadDeviceInfo{
    [self.timer invalidate];
    self.timer = nil;
}

//读取电压和温度个数
-(void)readVolAndTempCount
{
    
    self.hasReadVolTempValue = NO;
    NSArray *packArr = @[@{
        @"field":@"Pck_CellV_Cnt",
        @"regAddr":@(1000),
        @"bitWidth":@(16),
        @"ratio":@"1",
        @"cmdType":@(101)
    },@{
        @"field":@"Pck_Tmp_Cnt",
        @"regAddr":@(2000),
        @"bitWidth":@(16),
        @"ratio":@"1",
        @"cmdType":@(101)
    }];
    NSMutableArray *mtbArr = [NSMutableArray array];
    [packArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        [mtbArr addObject:settingModel];
        //根据不同的pack设置命令设备地址
        settingModel.cmdType = [NSString stringWithFormat:@"%ld",101 + self.packIndex];
    }];
    NSLog(@"---->读取单体个数和温度个数")
    self.cmdArray = mtbArr.copy;
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
    
    
}

#pragma mark ---------  读取具体的电压和温度 -----
-(void)readCellVoltageAndTemperature
{

    NSArray *volTempArr = @[@{
        @"field":@"Pck_CellV_1",
        @"regAddr":@(1001),
        @"bitWidth":@(16),
        @"ratio":@"1",
        @"cmdType":@(101)
    },@{
        @"field":@"Pck_Tmp_1",
        @"regAddr":@(2001),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(101)
    }];
    NSMutableArray *mtbArr = [NSMutableArray array];
    [volTempArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        if([settingModel.field isEqualToString:@"Pck_CellV_1"]){
            settingModel.readAddrCount = self.cellVolCount;//读取电压个数
        }
        if([settingModel.field isEqualToString:@"Pck_Tmp_1"]){
            settingModel.readAddrCount = self.cellTempCount;//读取温度个数
        }
        [mtbArr addObject:settingModel];
    }];
    NSLog(@"---->读取单体个数和温度个数")
    self.cmdArray = mtbArr.copy;
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
}

-(void)receiveDeviceMsg:(NSNotification*)no
{
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
   

    NSLog(@"------>收到设备信息:%@",dic);
  
            
   
    [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        if(obj.regAddr == [dic[CMD_ADDRESS] integerValue]){
            
            NSData *data = dic[CMD_ADDRESS_VALUE];
            NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
            NSLog(@"---->%@ = %@",obj.field,parse_content);
           
            
            [self.dataDic setObject:parse_content forKey:obj.field];
           
          
            NSLog(@"---->曲线数据:%@",self.lineDic);
            
            //读取到电芯电压数量
            if([obj.field isEqualToString:@"Pck_CellV_Cnt"]){
                self.cellVolCount = [parse_content integerValue];
            }
            
            //读取到温度数量
            if([obj.field isEqualToString:@"Pck_Tmp_Cnt"]){
                self.hasReadVolTempCount = YES;
                self.cellTempCount = [parse_content integerValue];
            }
            
            
            //读取到电压值
            if([obj.field isEqualToString:@"Pck_CellV_1"]){
               
                for (int i = 0; i < self.cellVolCount; i ++) {
                    NSData *volData = [data subdataWithRange:NSMakeRange(i*2, 2)];
                    NSInteger volIntValue = [JCDataConvert dataToInt:volData];
                    NSString *volStr = [NSString stringWithFormat:@"%ld",volIntValue];
                    if(self.volDataArr.count>i){
                        [self.volDataArr replaceObjectAtIndex:i withObject:volStr];
                        
                    }else{
                        [self.volDataArr addObject:volStr];
                    }
                    
                }
               
            }
            
            //读取到温度值
            if([obj.field isEqualToString:@"Pck_Tmp_1"]){
                self.hasReadVolTempValue = YES;
                for (int i = 0; i < self.cellTempCount; i ++) {
                    NSData *tempData = [data subdataWithRange:NSMakeRange(i*2, 2)];
                    double value = [JCDataConvert dataToInt:tempData]*[obj.ratio doubleValue];
                    NSNumber *num = [NSNumber numberWithDouble:value];
                    if(self.tempDataArr.count>i){
                        [self.tempDataArr replaceObjectAtIndex:i withObject:[num decimalPlacesWithRoundUpWithDigit:1]];
                    }else{
                        
                        [self.tempDataArr addObject:[num decimalPlacesWithRoundUpWithDigit:1]];
                    }
                   
                }
               //组装曲线数据
                NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                NSInteger timeInterval = [[NSDate date]timeIntervalSince1970]*1000;
                NSString *timeStr = [NSString stringWithFormat:@"%ld",timeInterval];
                NSString *volt = [NSString stringWithFormat:@"%@",self.volDataArr[self.cellIndex]];
                NSString *temp = [NSString stringWithFormat:@"%@",self.tempDataArr[self.cellIndex/2]];
                //高压的是4个电芯共用一个电芯温度
                if([CBLECenterMnger shareMnger].curPheral.isHighVoltage){
                    NSString *temp = [NSString stringWithFormat:@"%@",[self.tempDataArr safeObjectAtIndex:self.cellIndex/4]];
                }
                [mtbDic setObject:volt forKey:@"Pck_CellV"];
                [mtbDic setObject:temp forKey:@"Pck_Tmp"];
                [mtbDic setObject:timeStr forKey:@"time"];
                [mtbDic setObject:@"HH:mm:ss" forKey:@"timeFormat"];//电芯电压X时间定制格式,展示秒数
                NSLog(@"------>编号%ld的电压和温度:%@",self.cellIndex+1,mtbDic);
                [self shiftChartData:mtbDic.copy];
            }
        }
           
    }];

}

//数据左移
-(void)shiftChartData:(NSDictionary *)dic
{
    if(self.chartDataArr.count>=10){
        [self.chartDataArr removeObjectAtIndex:0];
        [self.chartDataArr addObject:dic];
    }else{
        //填充10个数据
        
        NSInteger timeInterval = [[NSDate date]timeIntervalSince1970]*1000;
        NSString *timeStr = [NSString stringWithFormat:@"%ld",timeInterval];
        for (int i = 0; i < 10; i++) {
            NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
            [mtbDic setObject:dic[@"Pck_CellV"] forKey:@"Pck_CellV"];
            [mtbDic setObject:dic[@"Pck_Tmp"] forKey:@"Pck_Tmp"];
            [mtbDic setObject:timeStr forKey:@"time"];
            [mtbDic setObject:@"HH:mm:ss" forKey:@"timeFormat"];//电芯电压X时间定制格式,展示秒数
            [_chartDataArr addObject:mtbDic];
        }
    }
    self.chartModel.allDataArray = self.chartDataArr;
    [self.chartView setChartModel:self.chartModel];
}

-(void)sendCmdFinish
{
    //读取完单体个数和温度个数就读具体的单体电压值和温度值
    if(self.hasReadVolTempCount){
        if(self.hasReadVolTempValue){
            [self startReadDeviceInfo];
        }else{
            [self readCellVoltageAndTemperature];
        }
        
    }else{
        //读取单体个数和温度个数,两个单体共用一个温度
        [self readVolAndTempCount];
    }

}





- (void)setupUI{
    kWeakSelf;
    QMUIButton *backBtn = [[QMUIButton alloc]init];
    [backBtn setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
           delegate.allowRotate = 0;
        if(@available(iOS 16.0, *)) {
            [weakSelf.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
            NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *ws = (UIWindowScene *)array[0];
            UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
            geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
            [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
                 //业务代码
            }];
        }else{
            NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
      
    }];
    _chartView = [[RHLocalBatteryCellChartView alloc] initWithFrame:CGRectMake(kSafe_top, 0,kUI_WINDOW_H - kSafe_top,kUI_WINDOW_W - kSafe_bottom) type:0];
    _chartView.isLandscape = YES;
    [self.bgView addSubview:_chartView];
    
    _titleLab = [[QMUILabel alloc]init];
    _titleLab.textColor = kCOLOR_HEX(@"#3F4443");
    _titleLab.font = kBOLDSYSTEMFONT(16);
    _titleLab.text = [NSString stringWithFormat:@"%@%ld#%@",@"电芯".rh_localized,self.cellIndex+1,@"实时数据曲线".rh_localized];
    [self.bgView addSubview:_titleLab];
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(backBtn);
        make.centerX.mas_offset(0);
    }];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.left.mas_offset(15);
        make.width.height.offset(40);
    }];
    
    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];

 

}
-(NSMutableArray *)chartDataArr
{
    if(!_chartDataArr){
        _chartDataArr = [NSMutableArray array];
    }
    return _chartDataArr;
}

-(NSMutableArray *)volDataArr
{
    if(!_volDataArr){
        _volDataArr = [NSMutableArray array];
    }
    return _volDataArr;
}

-(NSMutableArray *)tempDataArr
{
    if(!_tempDataArr){
        _tempDataArr = [NSMutableArray array];
    }
    return _tempDataArr;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
